import { Component, OnInit } from '@angular/core';
import {Path} from "../../../../portal/admin/admin-breadcrumb/breadcrumb";
import {PageSubject} from "../../../../util/page-subject";
import {MsgResult} from "../../../../models/msg-result";
import {PolluteDataService} from "./pollute-data.service";
import {OneDialogService} from "../../../../widgets/one-dialog/one-dialog.service";
import {ResponseUtil} from "../../../../util/response-util";
import {MsgConstants} from "../../../../constants/constants";
import {PolluteData} from "./pollute-data";
import {TableUtil} from "../../../../util/table-util";

declare var $;
declare var moment;

@Component({
  selector: 'app-pollute-data',
  templateUrl: './pollute-data.component.html',
  styleUrls: ['./pollute-data.component.css']
})
export class PolluteDataComponent implements OnInit {
  config;

  pollute: PolluteData;
  siteHtml: Array<any> = [];
  dropIndustry:Array<any>=[];
  dropRaiseDust:Array<any>=[];
  dropLampblack:Array<any>=[];
  dropSprayBooth:Array<any>=[];
  waterPollution:Array<any>=[];
  waterSurface:Array<any>=[];
  polluteType: string;
  table: any;

  constructor(
    private pageSubject: PageSubject,
    private PolluteDataService: PolluteDataService,
    private responseUtil: ResponseUtil,
    private tableUtil: TableUtil,
    private dialogService: OneDialogService,) {
    this.initObject();
  }

  ngOnInit() {
    $(".one-data-loadState").show();
    this.pushPage();
    this.siteButtonData();
    this.getDropData();
  }

  //面包屑导航
  pushPage() {
    let path = new Path("数据查询", "");
    this.pageSubject.pushPage("污染源数据", "", path);
  }

  /**
   * 实例化对象
   */
  private initObject() {
    this.pollute = new PolluteData("hourData", moment().subtract(1, "d").subtract(1, "h").format("YYYY-MM-DD HH") + ":00:00", moment().subtract(1, "h").format("YYYY-MM-DD HH") + ":00:00", "");
  }

  //按钮数据
  siteButtonData() {
    this.PolluteDataService.getUserSiteData().subscribe(
      result => this.responseUtil.success(result, this.siteButtonDataResult),
      message => this.responseUtil.error(message)
    );
  }
  private siteButtonDataResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.siteButtonDataDataTree(result.data);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }
  //站点按钮
  siteButtonDataDataTree(data) {
    data.indexOf("raiseDustSite") != -1 && this.siteHtml.push({
      "name": "raiseDustSite",
      "className": "raiseDust",
      "chinese": "扬尘"
    });
    data.indexOf("industrySite") != -1 && this.siteHtml.push({
      "name": "industrySite",
      "className": "industry",
      "chinese": "工业废气"
    });
    data.indexOf("waterPollutionSite") != -1 && this.siteHtml.push({
      "name": "waterPollutionSite",
      "className": "waterPollution",
      "chinese": "工业废水"
    });
    data.indexOf("lampblackSite") != -1 && this.siteHtml.push({
      "name": "lampblackSite",
      "className": "lampblack",
      "chinese": "油烟"
    });
    data.indexOf("sprayBoothSite") != -1 && this.siteHtml.push({
      "name": "sprayBoothSite",
      "className": "sprayBooth",
      "chinese": "喷漆房"
    });
    console.log(this.siteHtml[0]);
    if (this.siteHtml) {
      this.polluteType = this.siteHtml[0].className;
      $(".user_site_button").find(".btn:first").addClass("active");
      this.initTime();
      this.initSite();
      this.tableContent();
      this.tableContentData(this.pollute);
    } else {
      $(".one-content").html("暂无数据");
    }
  };




  //表格数据
  getDropData(){
    this.PolluteDataService.getPollutantSiteData().subscribe(
      result => this.responseUtil.success(result,this.getDropDataResult),
      message => this.responseUtil.error(message)
    );
  }
  private getDropDataResult = (result: MsgResult) =>{
    $(".one-data-loadState").hide();
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.getDrop(result.data);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }
  getDrop(data){
    $.each(data, function (index, dropData) {
      var type = dropData.siteTypeCode;
             if(type == "101"){
        this.dropIndustry.push({"siteCode":dropData.siteCode,"siteName":dropData.siteName});
      }else if(type == "102"){
        this.dropRaiseDust.push({"siteCode":dropData.siteCode,"siteName":dropData.siteName});
      }else if(type == "103"){
        this.dropLampblack.push({"siteCode":dropData.siteCode,"siteName":dropData.siteName});
      }else if(type == "104"){
        this.dropSprayBooth.push({"siteCode":dropData.siteCode,"siteName":dropData.siteName});
      }else if(type == "201"){
        this.waterPollution.push({"siteCode":dropData.siteCode,"siteName":dropData.siteName});
      }else if(type == "006" || type == "007" || type == "008" || type == "009" || type == "010" || type == "011"){
        this.waterSurface.push({"siteCode":dropData.siteCode,"siteName":dropData.siteName});
      }
    }.bind(this));
  }


  clickType(type){
  this.polluteType = type;
  $(".one-inline-container").html("");
}

  inputClick(siteCode,name,even){
    let aa=$(even.target).is(":checked");
    if(aa){
      $(".one-inline-container").append('<div class="btn btn-success" id='+siteCode+'>'+name+' <i class="glyphicon glyphicon-remove"></i></div>');
    }else{
      $(".one-inline-container").find("#"+siteCode).remove();
    }
  }


  //初始化时间插件
  initTime() {
    this.config = {
      timePicker: true,
      timePickerIncrement: 5,
      timePicker24Hour: true,
      parentEl: $(".wrapper"),
      maxDate: new Date(),
      locale: {
        format: "YYYY-MM-DD HH:00",
        separator: " 至 ",
        applyLabel: '确定',
        cancelLabel: '取消',
        fromLabel: '从',
        toLabel: '到',
        weekLabel: 'W',
        customRangeLabel: 'Custom Range',
        daysOfWeek: ["日", "一", "二", "三", "四", "五", "六"],
        monthNames: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
        firstDay: 1
      },
      startDate: moment().subtract({days: 1, hours: 1}).format("YYYY-MM-DD HH") + ":00",
      endDate: moment().subtract(1, "h").format("YYYY-MM-DD HH") + ":00"
    };
    $("#polluteDataDate").daterangepicker(this.config);
  }

  //样式
  initSite() {
    //点击站点列表
    $(".one-inline-btn").click(function () {
      $(this).find(".dropdown-menu").show();
    }).mouseleave(function () {
      $(this).find(".dropdown-menu").hide();
    });

    //点击站点列表中的删除图标
    $(".one-inline-container").on("click", ".btn>.glyphicon-remove", function () {
      $(this).parent().remove();
      if ($(".one-inline-container>.btn").length < 5) {
        $('.list-inline input').iCheck('enable');
      } else {
        $('.list-inline .icheckbox_minimal-green:not(.checked) input').iCheck('disable');
      }
      var btnId = $(this).parent().attr("id");
      $(".dropdown-menu label").each(function () {
        var id = $(this).find("input").attr("id");
        if (btnId == id) {
          $(this).find("input").iCheck('uncheck');
        }
      });
    });

    //查询站点
    $("#searchPollute").bind("input propertychange", function () {
      let searchSiteVal = $("#searchPollute").val();
      if (searchSiteVal) {
        $(".dropdown-menu label").each(function () {
          var text = $(this).text();
          if (text.indexOf(searchSiteVal) != -1) {
            $(this).parent().show();
          } else {
            $(this).parent().hide();
          }
        })
      } else {
        $(".dropdown-menu label").parent().show();
      }
    })


  }

  search() {
    $(".one-data-loadState").show();
    let startTime =  $.trim($("#polluteDataDate").val().split("至")[0]);
    let endTime =  $.trim($("#polluteDataDate").val().split("至")[1]);
    startTime+=startTime.split(" ").length==1?" 00:00:00":":00";
    endTime+=endTime.split(" ").length==1?" 00:00:00":":00";
    this.pollute.startTime = startTime;
    this.pollute.endTime = endTime;
    let checkedSiteListObj = [];
    $(".one-inline-container>.btn").each(function () {
      var id = $(this).attr("id");
      checkedSiteListObj.push(id);
    });
    this.pollute.siteCodes = checkedSiteListObj.join(",");
    this.tableContentData(this.pollute);
  }

  clickDataType(type) {
    this.pollute.dataType = type;
    if (type == "hourData") {
      this.config.locale.format = "YYYY-MM-DD HH:00";
      this.config.timePicker = true;
      this.config.startDate = moment().subtract({days: 1, hours: 1}).format("YYYY-MM-DD HH") + ":00:00";
      this.config.endDate = moment().subtract(1, "h").format("YYYY-MM-DD HH") + ":00:00";
    } else if (type == "dayData") {
      this.config.locale.format = "YYYY-MM-DD";
      this.config.timePicker = false;
      this.config.startDate = moment().subtract(6, "d").format("YYYY-MM-DD");
      this.config.endDate = moment().subtract(1, "d").format("YYYY-MM-DD");
    } else if (type == "minuteData") {
      this.config.locale.format = "YYYY-MM-DD HH:mm";
      this.config.timePicker = true;
      this.config.startDate = moment().subtract(30, "m").format("YYYY-MM-DD HH:mm") + ":00";
      this.config.endDate = moment().subtract(1, "m").format("YYYY-MM-DD HH:mm") + ":00";
    }
    $("#polluteDataDate").daterangepicker(this.config);
  }

  //表格数据
  tableContentData(obj) {
    let dataId = this.polluteType;
    console.log(dataId);
    if (dataId == "industry") {
      this.PolluteDataService.getIndustryData(obj).subscribe(
        result => this.responseUtil.success(result, this.tableContentDataResult),
        message => this.responseUtil.error(message)
      );
    } else if (dataId == "raiseDust") {
      this.PolluteDataService.getRaiseDustData(obj).subscribe(
        result => this.responseUtil.success(result, this.tableContentDataResult),
        message => this.responseUtil.error(message)
      );
    } else if (dataId == "waterPollution") {
      this.PolluteDataService.getWaterData(obj).subscribe(
        result => this.responseUtil.success(result, this.tableContentDataResult),
        message => this.responseUtil.error(message)
      );
    } else if (dataId == "lampblack") {
      this.PolluteDataService.getLampblackData(obj).subscribe(
        result => this.responseUtil.success(result, this.tableContentDataResult),
        message => this.responseUtil.error(message)
      );
    } else if (dataId == "sprayBooth") {
      let data = [];
      this.tableContentDataTree(data);
    }
  }
  private tableContentDataResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.tableContentDataTree(result.data);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }
  private tableContentDataTree(data) {
    $(".one-data-loadState").hide();
    this.tableContent();
    this.table.bootstrapTable("load", data);
  }

  //表格
  tableContent() {
    $(".one-table-area").html('<table class="table table-striped" id="polluteDataTable"></table>');
    let dataId = this.polluteType;
    let tableObj;
    if (dataId == "industry") {
      tableObj = {
        columns: [
          [{
            field: 'index',
            title: '排名',
            rowspan: 2,
            valign: "middle",
            width: 35
          }, {
            field: 'cityName',
            title: '城市',
            rowspan: 2,
            valign: "middle",
            align: "left",
            halign: "center",
            width: 50
          }, {
            field: 'companyName',
            title: '企业名称',
            rowspan: 2,
            valign: "middle",
            align: "left",
            halign: "center",
            width: 90
          }, {
            field: 'monitorTime',
            title: '监测时间',
            rowspan: 2,
            valign: "middle",
            width: 110,
            align: "left",
            halign: "center"
          }, {
            field: ' ',
            title: '烟尘',
            colspan: 2,
            width: 180
          }, {
            field: ' ',
            title: 'SO<sub>2</sub>',
            colspan: 2,
            width: 180
          }, {
            field: ' ',
            title: 'NO<sub>2</sub>',
            colspan: 2,
            width: 180
          }, {
            field: 'couFlow',
            title: '<p>烟气</p><p>流量（立方米）</p>',
            rowspan: 2,
            valign: "middle",
            width: 100,
            align: "right",
            halign: "center"
          }],
          [
            {
              field: 'avgStrength001',
              title: '浓度(mg/m<sup>3</sup>)',
              align: "right",
              width: 90,
              halign: "center"
            }, {
            field: 'pfl001',
            title: '排放量(kg)',
            align: "right",
            width: 90,
            halign: "center"
          }, {
            field: 'avgStrength002',
            title: '浓度(mg/m<sup>3</sup>)',
            align: "right",
            width: 90,
            halign: "center"
          }, {
            field: 'pfl002',
            title: '排放量(kg)',
            align: "right",
            width: 90,
            halign: "center"
          }, {
            field: 'avgStrength003',
            title: '浓度(mg/m<sup>3</sup>)',
            align: "right",
            width: 90,
            halign: "center"
          }, {
            field: 'pfl003',
            title: '排放量(kg)',
            align: "right",
            width: 90,
            halign: "center"
          }
          ]
        ],
        data: [],
        pagination: true,
        paginationLoop: false,
        striped: true,
        paginationPreText: "上一页",
        paginationNextText: "下一页",
        undefinedText: " ",
        height: $(window.innerHeight)[0] - 300,
        pageSize: 15,
        pageList: [10, 15, 20]
      };
    } else if (dataId == "raiseDust") {
      tableObj = {
        columns: [
          {
            field: 'index',
            title: '排名',
            width: 35
          }, {
            field: 'regionName',
            title: '区域名称',
            align: "left",
            halign: "center",
            width: 90
          }, {
            field: 'siteName',
            title: '站点名称',
            align: "left",
            halign: "center",
            width: 90
          }, {
            field: 'monitorTime',
            title: '监测时间',
            width: 110,
            align: "left",
            halign: "center"
          }, {
            field: 'pm10',
            title: 'PM10(μg/m3)',
            width: 120,
            align: "right",
            halign: "center"
          }, {
            field: 'pm25',
            title: 'PM2.5(μg/m3)',
            width: 120,
            align: "right",
            halign: "center"
          }, {
            field: 'temperature',
            title: '温度(C)',
            width: 120,
            align: "right",
            halign: "center"
          }, {
            field: 'humidity',
            title: '湿度(%rh)',
            width: 120,
            align: "right",
            halign: "center"
          }, {
            field: 'windSpeed',
            title: '风力',
            width: 120,
            align: "right",
            halign: "center"
          }, {
            field: 'windDirection',
            title: '风向',
            width: 120,
            align: "left",
            halign: "center"
          }
        ],
        data: [],
        pagination: true,
        paginationLoop: false,
        striped: true,
        paginationPreText: "上一页",
        paginationNextText: "下一页",
        undefinedText: " ",
        height: $(window.innerHeight)[0] - 300,
        pageSize: 15,
        pageList: [10, 15, 20]
      };
    } else if (dataId == "waterPollution") {
      tableObj = {
        columns: [
          [{
            field: 'index',
            title: '排名',
            rowspan: 2,
            valign: "middle",
            width: 35
          }, {
            field: 'cityName',
            title: '城市',
            rowspan: 2,
            valign: "middle",
            align: "left",
            halign: "center",
            width: 50
          }, {
            field: 'companyName',
            title: '企业名称',
            rowspan: 2,
            valign: "middle",
            align: "left",
            halign: "center",
            width: 90
          }, {
            field: 'monitorTime',
            title: '监测时间',
            rowspan: 2,
            valign: "middle",
            width: 110,
            align: "left",
            halign: "center"
          }, {
            field: ' ',
            title: 'COD',
            colspan: 2,
            width: 180
          }, {
            field: ' ',
            title: '氨氮',
            colspan: 2,
            width: 180
          }, {
            field: ' ',
            title: '总氮',
            colspan: 2,
            width: 180
          }, {
            field: 'couFlow',
            title: '<p>累计排放量(吨)</p>',
            rowspan: 2,
            valign: "middle",
            width: 100,
            align: "right",
            halign: "center"
          }],
          [
            {
              field: 'avgStrength001',
              title: '浓度(mg/m<sup>3</sup>)',
              align: "right",
              width: 90,
              halign: "center"
            }, {
            field: 'pfl001',
            title: '排放量(kg)',
            align: "right",
            width: 90,
            halign: "center"
          }, {
            field: 'avgStrength002',
            title: '浓度(mg/m<sup>3</sup>)',
            align: "right",
            width: 90,
            halign: "center"
          }, {
            field: 'pfl002',
            title: '排放量(kg)',
            align: "right",
            width: 90,
            halign: "center"
          }, {
            field: 'avgStrength003',
            title: '浓度(mg/m<sup>3</sup>)',
            align: "right",
            width: 90,
            halign: "center"
          }, {
            field: 'pfl003',
            title: '排放量(kg)',
            align: "right",
            width: 90,
            halign: "center"
          }
          ]
        ],
        data: [],
        pagination: true,
        paginationLoop: false,
        striped: true,
        paginationPreText: "上一页",
        paginationNextText: "下一页",
        undefinedText: " ",
        height: $(window.innerHeight)[0] - 300,
        pageSize: 15,
        pageList: [10, 15, 20]
      };
    } else if (dataId == "lampblack") {
      tableObj = {
        columns: [
          [{
            field: 'index',
            title: '序号',
            rowspan: 2,
            valign: "middle",
            width: 35
          }, {
            field: 'cityName',
            title: '城市',
            rowspan: 2,
            valign: "middle",
            align: "left",
            halign: "center",
            width: 50
          }, {
            field: 'companyName',
            title: '企业名称',
            rowspan: 2,
            valign: "middle",
            align: "left",
            halign: "center",
            width: 90
          }, {
            field: 'monitorTime',
            title: '监测时间',
            rowspan: 2,
            valign: "middle",
            width: 110,
            align: "left",
            halign: "center"
          }, {
            field: ' ',
            title: '处理前',
            colspan: 8,
            width: 320
          }, {
            field: ' ',
            title: '处理后',
            colspan: 8,
            width: 320
          }],
          [
            {
              field: 'before.concentration',
              title: '油烟浓度',
              align: "right",
              width: 40,
              halign: "center"
            }, {
            field: 'before.blowerState',
            title: '风机状态',
            align: "right",
            width: 40,
            halign: "center"
          }, {
            field: 'before.purifierState',
            title: '净化器状态',
            align: "right",
            width: 40,
            halign: "center"
          }, {
            field: 'before.cleanLiness',
            title: '清洁度',
            align: "right",
            width: 40,
            halign: "center"
          }, {
            field: 'before.systemState',
            title: '探头状态',
            align: "right",
            width: 40,
            halign: "center"
          }, {
            field: 'before.conlimit',
            title: '浓度阀值',
            align: "right",
            width: 40,
            halign: "center"
          }, {
            field: 'before.temp',
            title: '温度',
            align: "right",
            width: 40,
            halign: "center"
          }, {
            field: 'before.hum',
            title: '湿度',
            align: "right",
            width: 40,
            halign: "center"
          }, {
            field: 'after.concentration',
            title: '油烟浓度',
            align: "right",
            width: 40,
            halign: "center"
          }, {
            field: 'after.blowerState',
            title: '风机状态',
            align: "right",
            width: 40,
            halign: "center"
          }, {
            field: 'after.purifierState',
            title: '净化器状态',
            align: "right",
            width: 40,
            halign: "center"
          }, {
            field: 'after.cleanLiness',
            title: '清洁度',
            align: "right",
            width: 40,
            halign: "center"
          }, {
            field: 'after.systemState',
            title: '探头状态',
            align: "right",
            width: 40,
            halign: "center"
          }, {
            field: 'after.conlimit',
            title: '浓度阀值',
            align: "right",
            width: 40,
            halign: "center"
          }, {
            field: 'after.temp',
            title: '温度',
            align: "right",
            width: 40,
            halign: "center"
          }, {
            field: 'after.hum',
            title: '湿度',
            align: "right",
            width: 40,
            halign: "center"
          }
          ]
        ],
        data: [],
        pagination: true,
        paginationLoop: false,
        striped: true,
        paginationPreText: "上一页",
        paginationNextText: "下一页",
        undefinedText: " ",
        height: $(window.innerHeight)[0] - 300,
        pageSize: 15,
        pageList: [10, 15, 20]
      };
    } else {
      tableObj = {
        columns: [
          {
            field: 'index',
            title: '排名'
          }, {
            field: 'cityName',
            title: '城市名称',
            align: "left",
            halign: "center"
          }, {
            field: 'siteName',
            title: '站点名称',
            align: "left",
            halign: "center"
          }, {
            field: 'monitorTime',
            title: '监测时间'
          }, {
            field: 'pm10',
            title: 'PM10(μg/m3)',
            width: 120
          }, {
            field: 'pm25',
            title: 'PM2.5(μg/m3)',
            width: 120
          }, {
            field: 'temperature',
            title: '温度(C)',
            width: 120
          }, {
            field: 'humidity',
            title: '湿度(%rh)',
            width: 120
          }, {
            field: 'wind',
            title: '风力',
            width: 120
          }, {
            field: 'windDir',
            title: '风向',
            width: 120
          }
        ],
        data: [],
        pagination: true,
        paginationLoop: false,
        striped: true,
        paginationPreText: "上一页",
        paginationNextText: "下一页",
        undefinedText: " ",
        height: $(window.innerHeight)[0] - 300,
        pageSize: 15,
        pageList: [10, 15, 20]
      }
    }
    this.table = this.tableUtil.load("polluteDataTable", tableObj);
  }

//导出
  export() {
    let startTime;
    let endTime;
    startTime = $.trim($("#polluteDataDate").val().split("至")[0]);
    endTime = $.trim($("#polluteDataDate").val().split("至")[1]);
    startTime+=startTime.split(" ").length==1?" 00:00:00":":00";
    endTime+=endTime.split(" ").length==1?" 00:00:00":":00";
    this.pollute.startTime = startTime;
    this.pollute.endTime = endTime;
    let checkedSiteListObj = [];
    $(".one-inline-container>.btn").each(function () {
      var id = $(this).attr("id");
      checkedSiteListObj.push(id);
    });
    this.pollute.siteCodes = checkedSiteListObj.join(",");

    let baseUrl = location.protocol + "//" + location.host + "/";
    let polluteObj = this.polluteType;
    let requestUrl: string;
    if (polluteObj == "industry") {
      requestUrl = "api/exportExcel/industryPollutionDataExcelExport?format=json&";
    } else if (polluteObj == "raiseDust") {
      requestUrl = "api/exportExcel/raiseDustDataExcelExport?format=json&";
    } else if (polluteObj == "waterPollution") {
      requestUrl = "api/exportExcel/waterPollutionDataExcelExport?format=json&";
    } else if (polluteObj == "lampblack") {
      requestUrl = "api/exportExcel/lampBlackDataExcelExport?format=json&";
    } else {
      this.dialogService.info("暂无导出功能");
    }
    let objString = "endTime=" + this.pollute.endTime + "&startTime=" + this.pollute.startTime + "&dataType=" + this.pollute.dataType;
    if(polluteObj != "sprayBooth"){
      window.location.href = baseUrl + requestUrl + objString;
    }

  }

}


















